package org.monkey.example.pay.service.impl;

import io.seata.spring.annotation.GlobalTransactional;
import java.math.BigDecimal;
import org.monkey.common.constant.entity.ErrorResultEnum;
import org.monkey.common.constant.exception.BaseException;

import org.monkey.example.pay.dao.UserAmountDao;
import org.monkey.example.pay.entity.dto.UserAmountDto;
import org.monkey.example.pay.entity.form.PayForm;
import org.monkey.example.pay.entity.po.UserAmountPo;
import org.monkey.example.pay.service.UserAmountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.klock.annotation.Klock;
import org.springframework.boot.autoconfigure.klock.annotation.KlockKey;
import org.springframework.stereotype.Service;

@Service
@KlockKey("amount")
public class UserAmountServiceImpl implements UserAmountService {

  @Autowired
  UserAmountDao userAmountDao;

  @GlobalTransactional
  @Klock(keys = {"#payForm.accountId"}, waitTime = 2, leaseTime = 30)
  @Override
  public boolean amountReduce(PayForm payForm) {
    UserAmountPo userAmountPo = findByAccountId(payForm.getAccountId(), true);
    UserAmountDto userAmountDto = new UserAmountDto(userAmountPo);
    userAmountDto.setTotalAmount(
        userAmountDto.getTotalAmount().subtract(BigDecimal.valueOf(payForm.getAmount())));
    userAmountDao.updateById(new UserAmountPo(userAmountDto));
    // return true;
    throw new BaseException(ErrorResultEnum.TEST_ERROR);
  }

  private UserAmountPo findByAccountId(Long accountId, boolean checkNull) {
    UserAmountPo userAmountPo = userAmountDao.findByAccountId(accountId);
    if (checkNull && userAmountPo == null) {
      throw new BaseException(ErrorResultEnum.DATA_NOT_FOUNT,
          "could not fount useramount by accountId " + accountId);
    }
    return userAmountPo;
  }


}
